import Stats from './stats.min'

var stats = new Stats();
stats.setMode(0);
stats.domElement.style.position = 'absolute';
stats.domElement.style.right = '0px';
stats.domElement.style.top = '0px';
document.body.appendChild(stats.domElement);
let AnimationFrameRequest = {
    _autoNumber: 0,
    _actions: {},
    _isActive: false,
    _RAF: (function () {
        return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (callback) {
            return window.setTimeout(callback, 1000 / 60);
        };
    })().bind(window),
    _doFrame() {
        Object.keys(this._actions).filter(key => {
            let config = this._actions[key];
            if (!config || !config.frameCb) {
                return false;
            }
            config.frameCb.call(config.context || window);
        });
        if (this.active()) {
            stats.update();
            this._RAF(this._doFrame.bind(this));
        }
    },
    /**
     * @param frameCb {Function}
     * @param context {Object=}
     */
    register(frameCb, context) {
        let num = this._autoNumber++;
        this._actions[num] = {
            context,
            frameCb,
            active: true
        };
        if (!this.active()) {
            this.active(true);
        }
        return num;
    },
    /**
     * @param cb {Function}
     * @param timer {number}
     * @returns {*|number}
     */
    setInterval(cb, timer) {
        let lastTime = new Date().getTime();
        return this.register(function () {
            let thisTime = new Date().getTime();
            if (thisTime - lastTime >= timer) {
                cb.call(window);
                lastTime = thisTime;
            }
        })
    },
    /**
     * @param id {number}
     */
    cancellation(id) {
        if (!id) {
            return;
        }
        delete this._actions[id];
    },
    /**
     * @param b {boolean=undefined}
     * @returns {boolean}
     */
    active(b) {
        if (b != null && typeof b === 'boolean') {
            this._isActive = b;
            if (this._isActive) {
                this._doFrame();
            }
        }
        let tasks = Object.keys(this._actions);
        if (tasks.length === 0) {
            this._isActive = false;
        }
        return this._isActive;
    }
};
export default AnimationFrameRequest;